import React from 'react';
import { inject, observer } from 'mobx-react';
import {
  WeaDatePicker,
  WeaTable,
  WeaInputNumber,
  WeaCheckbox,
  WeaSearchGroup,
  WeaInput,
  WeaTableEditable,
  WeaLocaleProvider
} from 'ecCom';
const toJS = mobx.toJS;
const getLabel = WeaLocaleProvider.getLabel;

@inject('planProgramViewStore')
@observer
export default class WorkPlan extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchGroupPreviewVisible:true,
      searchGroupVisible: true,
      summarySpecialColums: [
        'begindate2',
        'enddate2',
        'days2',
        'result',
        'finishrate',
      ],
      selectedRowKeys: [], //选中行
    };
    this.store = this.props.planProgramViewStore;
    this.saveRef = ref => {
      this.refDom = ref;
    };
  }

  //设置预览表格列
  setPreviewColumns = () => {
    let fieldRows = toJS(this.store.fieldRows);
    fieldRows.sort((a, b) => {
      return a.showorder2 - b.showorder2
    })

    let columns = [];
    let totalWidth = this.refDom ? this.refDom.clientWidth : 1000;
    let totalWidthCount = 0
    fieldRows.map(v => {
      if (v.isshow2) {
        totalWidthCount += parseInt(v.showwidth2)
      }
    })
    fieldRows.map((v, i) => {
      if (
        v.isshow2 == '1' &&
        this.state.summarySpecialColums.indexOf(v.fieldname) == -1
      ) {
        let title = v.customname ? v.customname : v.showname
        title = v.ismust2 == '1' ? `${title}(${getLabel(30036, '必填')})` : title
        columns.push({

          title: title,
          dataIndex: v.fieldname,
          key: v.fieldname,
          ismust: v.ismust,
          ismust2: v.ismust2,
          // width:( parseInt(v.showwidth2) / totalWidthCount )*totalWidth  + 'px',
          width: v.showwidth2 + "%",
          com: [
            {
              type: 'text',
              key: v.fieldname,
              hasHiddenField: true,
              defaultValue: '',
              viewAttr: 2,
            },
          ],
        });
      }
    });
    this.store.setPlanPreColumns(columns);

    return columns;
  };

  getFieldNameColumn = (text, paramName) => {
    let { auth: { canedit, canview } } = this.store;
    let viewAttr = 2
    if (!canedit) {
      viewAttr = 1
    }
    return (
      <div>
        <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@6bw2we`}
          viewAttr={viewAttr}
          onChange={e => {
            this.store.fieldRows.map((v, i) => {

              if (text == getLabel('25532', '是否必填') && v['isshow2'] != '1') {
                return
              }
              if (v.fieldname != 'name') {
                v[paramName] = e;
              }
            });
          }}
        />{text}
      </div>
    );
  };
  checkBoxRender = (text, record, index, paramName) => {
    let viewAttr = 2;
    let { auth: { canedit, canview } } = this.store;
    if (
      record.fieldname == 'name' ||
      (paramName == 'ismust2' && record.isshow2 == '0')
      ||
      !canedit
    )
      viewAttr = 1;

    return (
      <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@vnn791`}
        viewAttr={viewAttr}
        value={text}
        onChange={e => this.onValueChange(e, paramName, record.id)}
      />
    );
  };
  inputRender(text, record, index, paramName) {
    let { auth: { canedit, canview } } = this.store;
    let viewAttr = 2
    if (!canedit) {
      viewAttr = 1
    }
    switch (paramName) {
      case 'customname':
        return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@xwjukg`}
          viewAttr={viewAttr}
          value={text}
          onChange={e => this.onValueChange(e, paramName, record.id)}
        ></WeaInput>
      case 'showorder2':
        return (
          <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@3zgd3y`}
            viewAttr={viewAttr}
            precision={2}
            value={text}
            onChange={e => this.onValueChange(e, paramName, record.id)}
          />
        );
      case 'showwidth2':
        return (
          <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@0vvolc`}
            min={0}
            viewAttr={viewAttr}
            value={text}
            onChange={e => this.onValueChange(e, paramName, record.id)}
          />
        );
    }
  }

  onValueChange = (e, paramName, id) => {
    this.store.fieldRows[id][paramName] = e;
    if ("isshow2" == paramName && e == '0') {
      this.store.fieldRows[id]['ismust2'] = e;
    }
  };

  getDIYColumns = () => {
    return [
      {
        title: getLabel('33331', '字段'),
        dataIndex: 'showname',
        key: 'showname',
        width: '20%',
      },
      {
        title: this.getFieldNameColumn(getLabel('15603', '是否显示'), 'isshow2'),
        dataIndex: 'isshow2',
        key: 'isshow2',
        width: '20%',
        render: (text, record, index) => {
          return this.checkBoxRender(text, record, index, 'isshow2');
        },
      },
      {
        title: this.getFieldNameColumn(getLabel('25532', '是否必填'), 'ismust2'),
        dataIndex: 'ismust2',
        key: 'ismust2',
        width: '20%',
        render: (text, record, index) => {
          return this.checkBoxRender(text, record, index, 'ismust2');
        },
      },
      // {
      //   title: getLabel('338','排序') ,
      //   dataIndex: 'showorder2',
      //   key: 'showorder2',
      //   render: (text, record, index) => {
      //     return this.inputRender (text, record, index, 'showorder2');
      //   },
      // },
      {
        title: getLabel('509086', '宽度比例(%)') + "(%)",
        dataIndex: 'showwidth2',
        key: 'showwidth2',
        width: '20%',
        render: (text, record, index) => {
          return this.inputRender(text, record, index, 'showwidth2');
        },
      },
      {
        title: getLabel('17607', '自定义名称'),
        dataIndex: 'customname',
        key: 'customname',
        width: '20%',
        render: (text, record, index) => {
          return this.inputRender(text, record, index, 'customname');
        },
      },
    ];
  };


  willDelete = (datas, keys) => {
    this.store.planDefaultRows = datas;
    return true;
  };

  getPreviewEditableTableConfig = () => {
    let config = {
      showAdd: this.store.auth.canedit,
      showDelete: this.store.auth.canedit,
      selectedRowKeys: this.state.selectedRowKeys,
      showTitle: true,
      showCopy: false,
      draggable: false,
      pushTitleIntoHeader: false,
      columns: this.setPreviewColumns(),
      buttonsType: 'inline',
      datas: toJS(this.store.planDefaultRows),
      willAdd: this.willAdd,
      willDelete: this.willDelete,
      tableProps: this.getTableProps(),
      getRowSelection: rowSelection => {
        return !this.store.auth.canedit ? false : rowSelection;
      },
    };
    if (!this.store.auth.canedit) {
      config.getRowSelection = () => { };
    }

    return config;
  };

  getTableProps = () => {
    let _this = this;
    let { auth: { canedit, canview }, fieldRows } = this.store;
    const { summarySpecialColums } = this.state;
    let dataSource = fieldRows.filter((v, i) => {
      if (summarySpecialColums.indexOf(v.fieldname) == -1) {
        return v;
      }
    });
    let totalWidth = 0
    dataSource.map(v => {
      if(v.isshow2){
        totalWidth += parseInt(v.showwidth2)
      }
    })
    return {
      onRowClick: (...arg) => {
        if (canedit) {
          _this.store.editModal.editData = toJS(arg[0]);
          _this.store.editModal.isShow = true;
        }
      },
      scroll: { x: totalWidth + '%' }

    };
  };

  //       begindate2 enddate2 days2 result finishrate
  getDIYTableConfig = () => {
    let { auth: { canedit, canview } } = this.store;
    const { summarySpecialColums } = this.state;
    let fieldRows = toJS(this.store.fieldRows);
    let dataSource = fieldRows.filter((v, i) => {
      if (summarySpecialColums.indexOf(v.fieldname) == -1) {
        return v;
      }
    });
    dataSource.sort((a, b) => {
      return a.showorder2 - b.showorder2
    })
    return {
      columns: this.getDIYColumns(),
      dataSource: dataSource,
      pagination: false,
      draggable: canedit ? true : false,
      onDrop: this.onDropEvent
    };
  };
  //拖拽排序
  onDropEvent = (data) => {

    data = data.map((d, i) => {
      d.id = i
      d.showorder2 = i
      return d
    })
    let rows = toJS(this.store.fieldRows)
    let idIndex = 20
    rows = rows.map((r, i) => {
      data.map(d => {
        if (r.fieldname == d.fieldname) {
          r.id = d.id
          r.showorder2 = d.showorder2
        } else {
          r.id = idIndex++
        }

      })
      return r
    })

    rows.sort((a, b) => {
      return a.showorder2 - b.showorder2
    })
    rows.map((v, i) => {
      v.id = i
    })
    this.store.fieldRows = []
    this.store.fieldRows = rows
  }

  willAdd = (datas, addData) => {
    let { editModal } = this.store;
    datas.pop();
    editModal.isShow = true;
    return datas;
  };
  onSearchGroupChange = (v) => {
    this.setState({ searchGroupVisible: v })
  }
  onSearchGroupPreviewChange = (v) => {
    this.setState({ searchGroupPreviewVisible: v })
  }
  onTitleClick = () => {
    this.setState({ searchGroupVisible: !this.state.searchGroupVisible })
  }
  onPreviewTitleClick = () => {
    this.setState({ searchGroupPreviewVisible: !this.state.searchGroupPreviewVisible })
  }
  render() {
    let { auth: { canedit, canview },isshowplan ,setState} = this.store;
    let viewAttr = canedit?2:1
    return (
      <div ref={this.saveRef}>
        <div className="preview-table">
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@50a0gx`}
          className="diy-column"
          title={<div className="diy-title" onClick={this.onPreviewTitleClick}>{<div>
              {getLabel('509083','工作计划预览') } 
            </div>}</div>}
          showGroup={this.state.searchGroupPreviewVisible}
          onVisibleChange={this.onSearchGroupPreviewChange}
        >
          <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@57xbhp`} {...this.getPreviewEditableTableConfig()} />

        </WeaSearchGroup>

        {(canview || canedit) &&
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@s4hun5`}
            className="diy-column"
            title={<div className="diy-title" onClick={this.onTitleClick}>{getLabel('509087', '自定义计划列字段')}</div>}
            showGroup={this.state.searchGroupVisible}
            onVisibleChange={this.onSearchGroupChange}
          >
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@3956bq`} {...this.getDIYTableConfig()} />
          </WeaSearchGroup>}
          </div>
      </div>
    );
  }
}
